#include "TCPRecognizeClient.h"
#include <QMessageBox>
#include "mainwindow.h"

TCPRecognizeClient::TCPRecognizeClient(QWidget *parent)
{
    this->setParent(parent);

    Init();
}

TCPRecognizeClient::~TCPRecognizeClient()
{
    if (socket->isOpen())
        socket->close();
}

void TCPRecognizeClient::Init()
{
    socket = new QTcpSocket(this);
    connect(socket, &QTcpSocket::readyRead, this, &TCPRecognizeClient::readSocket);
    connect(socket, &QTcpSocket::disconnected, this, &TCPRecognizeClient::discardSocket);
    connect(socket, &QAbstractSocket::errorOccurred, this, &TCPRecognizeClient::displayError);
}

void TCPRecognizeClient::ConnectServer(QString strIP, int port)
{
    socket->connectToHost(QHostAddress(strIP), port);

    if (socket->waitForConnected())
        qDebug() << QString("连接到服务器 %1:%2 成功！").arg(strIP).arg(port);
    else {
        qDebug() << QString("出现TCP/IP错误: %1.").arg(socket->errorString());
        QMessageBox::information(nullptr, "错误", QString("连接服务器 %1:%2 失败！")
                                                      .arg(strIP).arg(port));
        exit(EXIT_FAILURE);
    }
}

void TCPRecognizeClient::readSocket()
{
    QByteArray buffer;

    QDataStream socketStream(socket);
    socketStream.setVersion(QDataStream::Qt_6_5);

    QByteArray bytes = socket->readAll();
    QString message = QString::fromUtf8(bytes);

    emit this->newResultMessage(message);
}

void TCPRecognizeClient::discardSocket()
{
    socket->deleteLater();
    socket = nullptr;

    qDebug() << ("断开连接!");
}

void TCPRecognizeClient::displayError(QAbstractSocket::SocketError socketError)
{
    switch (socketError) {
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        qDebug() << ("The host was not found. Please check the host name and port settings.");
        break;
    case QAbstractSocket::ConnectionRefusedError:
        qDebug() << ("The connection was refused by the peer. Make sure QTCPServer is running, and "
                     "check that the host name and port settings are correct.");
        break;
    default:
        qDebug() << (QString("The following error occurred: %1.").arg(socket->errorString()));
        break;
    }
}

void TCPRecognizeClient::sendProtocolMessage(QString str)
{
    if (socket) {
        if (socket->isOpen()) {
            QDataStream socketStream(socket);
            socketStream.setVersion(QDataStream::Qt_5_15);

            QByteArray header;
            header.prepend(
                QString("fileType:message,fileName:null,fileSize:%1;").arg(str.size()).toUtf8());
            header.resize(128);

            QByteArray byteArray = str.toUtf8();
            byteArray.prepend(header);

            socketStream << byteArray;
        } else
            qDebug() << ("Socket doesn't seem to be opened");
    } else
        qDebug() << ("QTCPClient : Not connected");
}

void TCPRecognizeClient::sendRawMessage(QString str)
{
    if (socket) {
        if (socket->isOpen()) {
            QDataStream socketStream(socket);
            socketStream.setVersion(QDataStream::Qt_6_5);
            QByteArray byteArray = str.toUtf8();
            //QByteArray byteArray = QStringLiteral("Hello").toUtf8();
            //socketStream << byteArray;
            socketStream.writeRawData(byteArray, byteArray.length());
        } else
            qDebug() << ("Socket doesn't seem to be opened");
    } else
        qDebug() << ("QTCPClient : Not connected");
}

void TCPRecognizeClient::sendAttachment(QString filePath)
{
    if (socket) {
        if (socket->isOpen()) {
            if (filePath.isEmpty()) {
                qDebug() << ("You haven't selected any attachment!");
                return;
            }

            QFile m_file(filePath);
            if (m_file.open(QIODevice::ReadOnly)) {
                QFileInfo fileInfo(m_file.fileName());
                QString fileName(fileInfo.fileName());

                QDataStream socketStream(socket);
                socketStream.setVersion(QDataStream::Qt_5_15);

                QByteArray header;
                header.prepend(QString("fileType:attachment,fileName:%1,fileSize:%2;")
                                   .arg(fileName)
                                   .arg(m_file.size())
                                   .toUtf8());
                header.resize(128);

                QByteArray byteArray = m_file.readAll();
                byteArray.prepend(header);

                socketStream.setVersion(QDataStream::Qt_5_15);
                socketStream << byteArray;
            } else
                qDebug() << ("QTCPClient : Attachment is not readable!");
        } else
            qDebug() << ("QTCPClient : Socket doesn't seem to be opened");
    } else
        qDebug() << ("QTCPClient : Not connected");
}
